package com.shioirikukuri.util;

import com.aliyun.auth.credentials.Credential;
import com.aliyun.auth.credentials.provider.StaticCredentialProvider;
import com.aliyun.sdk.service.dysmsapi20170525.AsyncClient;
import com.aliyun.sdk.service.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.sdk.service.dysmsapi20170525.models.SendSmsResponse;
import com.google.gson.Gson;
import darabonba.core.client.ClientOverrideConfiguration;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
public class SmsService {

	@Autowired
	private RedisTemplate<String, String> redisTemplate;

	/**
	 * 发送短信验证码
	 */
	public void sendCode(String phoneNumber, String code) throws Exception {
		// 配置认证信息
		StaticCredentialProvider provider = StaticCredentialProvider.create(Credential.builder()
				.accessKeyId("LTAI5tKE288Hz3eNJR8wr36w")
				.accessKeySecret("hVxAl5bd23pO68qyB2x09dskD18Trt")
				.build());

		// 配置客户端
		AsyncClient client = AsyncClient.builder()
				.region("cn-shenzhen") // 设置区域 ID
				.credentialsProvider(provider) // 设置认证信息
				.overrideConfiguration(
						ClientOverrideConfiguration.create()
								.setEndpointOverride("dysmsapi.aliyuncs.com") // 设置 API 端点
				)
				.build();

		// 配置短信发送请求参数
		SendSmsRequest sendSmsRequest = SendSmsRequest.builder()
				.phoneNumbers(phoneNumber) // 接收短信的手机号
				.signName("阿里云短信测试") // 短信签名
				.templateCode("SMS_154950909") // 短信模板 ID
				.templateParam("{\"code\":\"" + code + "\"}") // 短信模板参数
				.build();

		// 发送短信
		SendSmsResponse response = client.sendSms(sendSmsRequest).get();
		System.out.println("短信发送结果：" + new Gson().toJson(response));

		// 关闭客户端
		client.close();

		// 将验证码存储到 Redis，有效期 5 分钟
		redisTemplate.opsForValue().set("sms_code:" + phoneNumber, code, 5, TimeUnit.MINUTES);
	}

	/**
	 * 验证短信验证码
	 */
	public boolean verifyCode(String phoneNumber, String code) {
		String storedCode = redisTemplate.opsForValue().get("sms_code:" + phoneNumber);
		return code.equals(storedCode);
	}
}